package com.acane.instagram.feature.home

import android.annotation.SuppressLint
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.compose.animation.AnimatedContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.notification.NotificationViewModel
import com.acane.instagram.feature.post.PostViewModel
import com.acane.instagram.feature.post.UserCommentBar
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.max

@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@Composable
fun HomeRoute(
    toFriend: () -> Unit = {},
    toProfile: (String) -> Unit = {},
    viewModel: HomeViewModel = viewModel(),
    toNotification: () -> Unit,
) {
    val postDatum by viewModel.postDatum.collectAsState()
    val userDatum by viewModel.userDatum.collectAsState()
    val isFollowingMap by viewModel.isFollowingMap.collectAsState() // 收集 isFollowingMap 的状态
    HomeScreen(
        postInfoList = postDatum,
        userInfoList = userDatum,
        toLikeMessage = {
            // 点赞
        },
        toFriend = toFriend,
        toFollowingMedia = {
            // 关注
        },
        toProfile = toProfile,
        toNotification = toNotification,
        isFollowingMap = isFollowingMap,
        homeViewModel = viewModel,
    )
}

@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
@SuppressLint("CoroutineCreationDuringComposition")
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HomeScreen(
    toProfile: (String) -> Unit,
    userInfoList: List<UserInfo>,
    postInfoList: List<PostInfo>,
    toLikeMessage: () -> Unit = {},
    toFriend: () -> Unit = {},
    toFollowingMedia: () -> Unit = {},
    toNotification: () -> Unit,
    isFollowingMap: Map<String, Boolean>, // 新增参数
    notificationViewModel: NotificationViewModel = viewModel(),
    postViewModel: PostViewModel = viewModel(),
    homeViewModel: HomeViewModel,
) {
    val listState = rememberLazyListState() // 添加 LazyListState
    var currentVisibleVideoIndex by remember { mutableIntStateOf(-1) } // 定义当前播放的视频索引
    val commentBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    // 添加状态变量来跟踪回复的评论
    var replyToComment by remember { mutableStateOf<CommentDTO?>(null) }

    var selectedPostUser by remember { mutableStateOf<UserInfo?>(null) }


    val postId by homeViewModel.postId.collectAsState(initial = null) // 监听 postId 的变化

    val scope = rememberCoroutineScope()
    val focusRequester = remember { FocusRequester() }

    // 下拉刷新
    val refreshState by homeViewModel.refresh.collectAsState()

    val swipeRefresh = rememberSwipeRefreshState(isRefreshing = refreshState)
    // 评论底部弹窗
    ModalBottomSheetLayout(
        sheetState = commentBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            val comments by homeViewModel.comments.collectAsState()
            val commentData = comments.filter { it.postId == postId }

            Log.d("commentDatum", "${commentData}\npostId:$postId")
            val lazyListState = rememberLazyListState()
            LaunchedEffect(comments.size) {
                if (comments.isNotEmpty()) {
                    lazyListState.animateScrollToItem(comments.size - 1)
                }
            }
            Column(
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                if (commentData.isEmpty()) {

                    LazyColumn(
                        state = lazyListState,
                        modifier = Modifier
                            .fillMaxSize()
                            .weight(1f),
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .wrapContentSize(align = Alignment.TopCenter)

                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.bar_horizontal),
                                    contentDescription = "bar",
                                )
                            }
                        }
                        item {
                            Text(
                                text = "还没有评论",
                                modifier = Modifier.padding(16.dp),
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold,
                            )
                            Text(
                                text = "发起对话。",
                                fontSize = 12.sp,
                                color = InstagramDarkGray
                            )
                        }
                    }
                    UserCommentBar(
                        postViewModel = postViewModel,
                        onSendComment = {
                            val newComment = postId?.let {
                                CommentDTO(
                                    id = "",
                                    commenterId = SessionManager.currentUser?.id!!,
                                    postId = it,
                                    content = postViewModel.caption,
                                    timestamp = "",
                                    likes = 0,
                                    parentId = replyToComment?.id ?: "",
                                )
                            }
                            newComment?.let { homeViewModel.sendComment(it) }

                            postId?.let {
                                notificationViewModel.sendMessageNotification(
                                    commenterId = SessionManager.currentUser?.id!!,
                                    postId = it,
                                    content = postViewModel.caption,
                                )
                            }
                            Log.d("HomeRoute", "🟢 发送评论：${postViewModel.caption}")
                            postViewModel.caption = ""
                            replyToComment = null

                        },
                        replyToComment = replyToComment,
                        focusRequester = focusRequester,
                    )
                } else {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f)
                    ) {
                        // 添加 Bar
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .wrapContentSize(align = Alignment.Center)
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.bar_horizontal),
                                    contentDescription = "bar",
                                )
                            }
                        }
                        // 标题区域
                        item {
                            Row(
                                modifier = Modifier.fillMaxWidth(), // 添加宽度约束
                                horizontalArrangement = Arrangement.Center
                            ) {
                                androidx.compose.material3.Text(
                                    text = "评论",
                                    fontWeight = FontWeight.Bold,
                                    fontSize = 12.sp
                                )
                            }
                        }
                        // 分割线
                        item {
                            Divider(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 2.dp)
                            )
                        }
                        // 评论区域
                        item {
                            val groupedComments = commentData.groupBy {
                                when {
                                    it.parentId.isNullOrEmpty() -> "root"
                                    else -> it.parentId
                                }
                            }
                            selectedPostUser?.let {
                                CommentList(
                                    comments = groupedComments["root"] ?: emptyList(),
                                    groupedComments = groupedComments,
                                    onReplyClick = { replyToComment = it },
                                    notificationViewModel = notificationViewModel,
                                    homeViewModel = homeViewModel,
                                    scope = scope,
                                    selectedPostUser = it,
                                    toProfile = toProfile,
                                    commentBottomSheetState = commentBottomSheetState,
                                    focusRequester = focusRequester,
                                )
                            }
                        }

                    }
                    UserCommentBar(
                        postViewModel = postViewModel,
                        onSendComment = {
                            val newComment = postId?.let {
                                CommentDTO(
                                    id = "",
                                    commenterId = SessionManager.currentUser?.id!!,
                                    postId = it,
                                    content = postViewModel.caption,
                                    timestamp = "",
                                    likes = 0,
                                    parentId = replyToComment?.id ?: ""
                                )
                            }
                            newComment?.let { homeViewModel.sendComment(it) }

                            postId?.let {
                                notificationViewModel.sendMessageNotification(
                                    commenterId = SessionManager.currentUser?.id!!,
                                    postId = it,
                                    content = postViewModel.caption,
                                )
                            }
                            Log.d("HomeRoute", "🟢 发送评论：${postViewModel.caption}")
                            postViewModel.caption = ""
                            replyToComment = null // 清除回复状态
                        }, // 传递回复的评论
                        replyToComment = replyToComment,
                        focusRequester = focusRequester,
                    )
                }
            }

        }
    ) {
        // 下拉刷新
        SwipeRefresh(state = swipeRefresh, onRefresh = {
            homeViewModel.startRefresh()
        }) {
            Scaffold(
                topBar = {
                    HomeTopBar(
                        toLikeMessage, toFriend, toFollowingMedia, toNotification,
                    )
                }
            ) { paddingValues ->
                // 推荐用户列表
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    item {
                        RecommendUserList(userInfoList, toProfile)
                    }
                    // 分割线
                    item {
                        Divider(
                            modifier = Modifier,
                            color = InstagramLightGray
                        )
                    }
                    // 推荐帖子列表
                    postInfoList.forEachIndexed { index, post ->
                        item {
                            RecommendPostItem(
                                postInfo = post,
                                toProfile = toProfile,
                                isAutoPlay = currentVisibleVideoIndex == index, // 传递播放状态
                                isFollowingMap = isFollowingMap, // 传递 isFollowingMap,
                                onCommentClick = {
                                    scope.launch {
                                        homeViewModel.updatePostId(post.id)
                                        homeViewModel.loadComments(post.id)
                                        selectedPostUser = post.user
                                        commentBottomSheetState.show()
                                    }
                                }
                            )
                        }
                    }
                }
            }
        }
    }


    // 添加滚动监听
    HandleVideoPlayback(listState, postInfoList, currentVisibleVideoIndex) { index ->
        currentVisibleVideoIndex = index // 更新当前播放的索引
    }
}


@OptIn(ExperimentalMaterialApi::class)
@Composable
fun CommentList(
    comments: List<CommentDTO>,
    groupedComments: Map<String, List<CommentDTO>>,
    onReplyClick: (CommentDTO) -> Unit,
    notificationViewModel: NotificationViewModel,
    homeViewModel: HomeViewModel,
    scope: CoroutineScope,
    selectedPostUser: UserInfo,
    toProfile: (String) -> Unit,
    isTopLevel: Boolean = true, // 新增层级标记
    commentBottomSheetState: ModalBottomSheetState,
    focusRequester: FocusRequester,
) {
    comments.forEach { comment ->
        // 渲染当前层级的评论
        CommentItem(
            scope = scope,
            comment = comment,
            selectedPostUser = selectedPostUser,
            notificationViewModel = notificationViewModel,
            toProfile = toProfile,
            onReplyClick = onReplyClick,
            indent = if (isTopLevel) 0 else 1, // 非顶层统一缩进24dp
            commentBottomSheetState = commentBottomSheetState,
            focusRequester = focusRequester,
        )

        // 获取当前评论的所有回复
        val replies = groupedComments[comment.id] ?: emptyList()

        // 只在顶层处理展开/折叠逻辑
        if (isTopLevel) {
            var showReplies by remember { mutableStateOf(false) }

            if (replies.isNotEmpty()) {
                // 展开/折叠按钮
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 48.dp)
                        .clickable { showReplies = !showReplies }
                ) {
                    Text(
                        text = if (showReplies) "隐藏回复" else "————查看回复",
                        fontSize = 10.sp,
                        color = InstagramDarkGray
                    )
                }

                // 递归渲染子评论（非顶层）
                if (showReplies) {
                    CommentList(
                        comments = replies,
                        groupedComments = groupedComments,
                        onReplyClick = onReplyClick,
                        notificationViewModel = notificationViewModel,
                        homeViewModel = homeViewModel,
                        scope = scope,
                        selectedPostUser = selectedPostUser,
                        toProfile = toProfile,
                        isTopLevel = false,
                        commentBottomSheetState = commentBottomSheetState,
                        focusRequester = focusRequester
                    )
                }
            }
        } else {
            // 非顶层直接递归渲染子评论（无展开按钮）
            if (replies.isNotEmpty()) {
                CommentList(
                    comments = replies,
                    groupedComments = groupedComments,
                    onReplyClick = onReplyClick,
                    notificationViewModel = notificationViewModel,
                    homeViewModel = homeViewModel,
                    scope = scope,
                    selectedPostUser = selectedPostUser,
                    toProfile = toProfile,
                    isTopLevel = false,
                    commentBottomSheetState = commentBottomSheetState,
                    focusRequester = focusRequester
                )
            }
        }
    }
}


@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun CommentItem(
    scope: CoroutineScope,
    comment: CommentDTO?,
    selectedPostUser: UserInfo,
    notificationViewModel: NotificationViewModel,
    toProfile: (String) -> Unit,
    onReplyClick: (CommentDTO) -> Unit,
    indent: Int, // 缩进级别
    commentBottomSheetState: ModalBottomSheetState,
    focusRequester: FocusRequester,
) {
    //val focusRequester = remember { FocusRequester() }
    var commenter by remember { mutableStateOf(UserInfo()) }
    scope.launch {
        val response = withContext(Dispatchers.IO) {
            comment?.let { MyRetrofitDatasource.getUserById(it.commenterId) }
        }
        commenter = response?.data!!
    }

    val (isLiked, setIsLiked) = remember { mutableStateOf(false) }
    var likes by remember { mutableStateOf(comment?.likes) }
    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        scope.launch(Dispatchers.IO) {
            val isCommentLikedResponse = MyRetrofitDatasource.judgeIsCommentLiked(
                comment?.id,
                SessionManager.currentUser?.id
            ).data == true
            setIsLiked(isCommentLikedResponse)
            Log.d("HomeRoute", "🟢 初始化点赞状态：$isCommentLikedResponse")
        }
    }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 10.dp)
            .padding(start = 24.dp * indent) // 根据缩进级别
    ) {
        // 头像左边占位
        Spacer(modifier = Modifier.size(8.dp))
        //发布者头像
        AsyncImage(model = commenter.avatar?.let {
            val url = "${Config.ADDRESS}avatars/$it"
            Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
            url
        } ?: run {
            Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
            R.drawable.ic_default_avatar
        },
            contentDescription = "发布者头像",
            modifier = Modifier
                .size(30.dp)
                .clip(CircleShape)
                .background(Color.Transparent)
                .clickableNoRipple {
                    commenter.id?.let { toProfile(it) }
                    scope.launch {
                        commentBottomSheetState.hide()
                    }
                },
            contentScale = ContentScale.Crop,
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )
        Spacer(modifier = Modifier.size(8.dp))
        Column(
            modifier = Modifier.weight(1f)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(
                    text = commenter.nickName ?: "未知用户",
                    fontSize = 10.sp,
                    modifier = Modifier.padding(start = 8.dp, end = 8.dp)
                )
                comment?.let {
                    Text(
                        text = it.timestamp,
                        fontSize = 10.sp,
                        color = InstagramDarkGray,
                    )
                }
            }
            comment?.let {
                Text(
                    text = it.content,
                    fontSize = 12.sp,
                    modifier = Modifier.padding(start = 8.dp)
                )
            }
            Spacer(modifier = Modifier.size(5.dp))
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "回复",
                    fontSize = 10.sp,
                    color = InstagramDarkGray,
                    modifier = Modifier
                        .padding(start = 8.dp)
                        .clickable {
                            comment?.let { onReplyClick(it) }
                            focusRequester.requestFocus()
                        }
                )
            }
        }
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            AnimatedContent(targetState = isLiked) { targetIsLiked ->
                Image(
                    painter = painterResource(id = if (targetIsLiked) R.drawable.heart_filled else R.drawable.heart),
                    contentDescription = "点赞图标",
                    contentScale = ContentScale.Fit,
                    modifier = Modifier
                        .size(30.dp)
                        .padding(8.dp)
                        .clickable {
                            val newIsLiked = !isLiked // 先计算新状态
                            setIsLiked(newIsLiked)    // 立即更新本地状态

                            if (newIsLiked) {         // 根据新状态执行操作
                                likes = likes?.plus(1)
                                scope.launch {
                                    Log.d("UserPostList", "被点赞的评论：$comment")
                                    comment?.let {
                                        MyRetrofitDatasource.likeComment(
                                            it.id
                                        )
                                    }
                                    comment?.let {
                                        notificationViewModel.sendCommentLikeNotification(
                                            SessionManager.currentUser?.id!!, it.id
                                        )
                                    }
                                }
                            } else {
                                likes = likes?.minus(1)
                                scope.launch {
                                    comment?.let {
                                        MyRetrofitDatasource.unLikeComment(
                                            it.id
                                        )
                                    }
                                }
                            }
                        },
                )
            }
            androidx.compose.material.Text(
                text = likes.toString(),
                fontSize = 10.sp,
                color = InstagramDarkGray,
            )
        }
    }
}


// HomeScreen.kt
@Composable
fun HandleVideoPlayback(
    listState: LazyListState,
    posts: List<PostInfo>,
    currentVisibleVideoIndex: Int,
    onIndexChange: (Int) -> Unit // 回调函数，用于更新索引
) {
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo }
            .collect { visibleItems ->
                // 找到第一个完全可见的视频项
                val visibleVideoItem = visibleItems.find { item ->
                    val post = posts.getOrNull(item.index)
                    post?.urls?.firstOrNull()?.endsWith(".mp4") == true &&
                            listState.isItemVisible(item.index) // 使用自定义的 isItemVisible 函数

                }

                // 更新当前播放的索引
                onIndexChange(visibleVideoItem?.index ?: -1)
            }
    }

}

private fun LazyListState.isItemVisible(index: Int): Boolean {
    return layoutInfo.visibleItemsInfo.any { item ->
        item.index == index &&
                // 可见部分至少占项的 80%（可根据需要调整）
                (item.size - max(0, -item.offset) - max(
                    0,
                    item.offset + item.size - layoutInfo.viewportEndOffset
                )) / item.size.toFloat() > 0.8f
    }
}

@Composable
fun RecommendPostItem(
    postInfo: PostInfo,
    toProfile: (String) -> Unit,
    isAutoPlay: Boolean, // 新增参数
    homeViewModel: HomeViewModel = viewModel(),
    isFollowingMap: Map<String, Boolean>, // 新增参数
    onCommentClick: () -> Unit,
) {
    val context = LocalContext.current
    val isFollowing = isFollowingMap[postInfo.user.id] ?: false // 使用 isFollowingMap 获取状态
    val (isLiked, setIsLiked) = remember { mutableStateOf(false) }
    val (isCollected, setIsCollected) = remember { mutableStateOf(false) }
    var likes by remember { mutableStateOf(postInfo.likeCount) }
    var isExpanded by remember { mutableStateOf(false) } // 添加展开状态


    val notificationViewModel: NotificationViewModel = viewModel()
    val scope = rememberCoroutineScope()


    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        scope.launch(Dispatchers.IO) {
            val isLikedResponse = MyRetrofitDatasource.judgeIsLiked(
                postInfo.id,
                SessionManager.currentUser?.id
            ).data == true
            setIsLiked(isLikedResponse)
            Log.d("HomeRoute", "🟢 初始化点赞状态：$isLikedResponse")
        }
    }
    // 初始化收藏状态
    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        scope.launch(Dispatchers.IO) {
            val isCollectedResponse = MyRetrofitDatasource.judgeIsCollected(
                postInfo.id,
                SessionManager.currentUser?.id
            ).data == true

            setIsCollected(isCollectedResponse)
            Log.d("HomeRoute", "🟢 初始化收藏状态：$isCollectedResponse")
        }
    }
    // 初始化关注状态
    LaunchedEffect(Unit) {
        scope.launch(Dispatchers.IO) {
            val isFollowingResponse = MyRetrofitDatasource.judgeIsFollowed(
                postInfo.user.id!!,
                SessionManager.currentUser?.id
            ).data == true
            homeViewModel.setIsFollowing(postInfo.user.id, isFollowingResponse)
        }
    }


    Column(
        modifier = Modifier
            .padding(vertical = 8.dp),
        horizontalAlignment = Alignment.Start
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Spacer(modifier = Modifier.size(8.dp))
                //发布者头像
                AsyncImage(
                    model = postInfo.user.avatar?.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
                        url
                    } ?: run {
                        Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
                        R.drawable.ic_default_avatar
                    },
                    contentDescription = "发布者头像",
                    modifier = Modifier
                        .size(30.dp)
                        .clip(CircleShape)
                        .background(Color.Transparent)
                        .clickableNoRipple {
                            postInfo.user.id?.let { toProfile(it) }
                        },
                    contentScale = ContentScale.Crop,
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
                Spacer(modifier = Modifier.width(8.dp)) // 添加左右间距
                //昵称
                postInfo.user.nickName?.let {
                    Text(
                        text = it,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.Black
                    )
                }
                Spacer(modifier = Modifier.weight(1.0f)) // 添加左右间距
                // 关注按钮
                if (!isFollowing && postInfo.user.id != SessionManager.currentUser?.id) {
                    Button(
                        onClick = {
                            // 发送关注请求
                            scope.launch(Dispatchers.IO) {
                                homeViewModel.sendFollowRequest(
                                    postInfo.user.id!!,
                                    SessionManager.currentUser?.id!!
                                )
                            }
                            homeViewModel.setIsFollowing(postInfo.user.id!!, true)
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = InstagramLightGray,
                            contentColor = InstagramDarkGray
                        ),
                        modifier = Modifier
                            .height(30.dp)
                            .padding(horizontal = 4.dp), // 减少水平内边距
                        shape = RoundedCornerShape(5.dp),
                        elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                        contentPadding = PaddingValues(
                            horizontal = 8.dp,
                            vertical = 0.dp
                        ) // 设置内容内边距
                    ) {
                        androidx.compose.material3.Text(
                            text = "关注",
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
                Image(
                    painter = painterResource(id = R.drawable.options_vertical),
                    contentDescription = "options",
                    modifier = Modifier.size(24.dp)
                )
            }

        }
        Spacer(modifier = Modifier.height(8.dp)) // 添加左右间距
        ImageCarousel(
            postInfo = postInfo,
            isLiked = isLiked,
            isCollected = isCollected,
            onLikeClick = {
                val newIsLiked = !isLiked // 先计算新状态
                setIsLiked(newIsLiked)    // 立即更新本地状态
                if (newIsLiked) {         // 根据新状态执行操作
                    likes += 1
                    scope.launch {
                        MyRetrofitDatasource.likePost(postInfo.id)
                        notificationViewModel.sendLikeNotification(
                            SessionManager.currentUser?.id!!,
                            postInfo.id
                        )
                    }
                } else {
                    likes -= 1
                    scope.launch {
                        MyRetrofitDatasource.unlikePost(postInfo.id)
                    }
                }
            },
            isAutoPlay = isAutoPlay,
            onCommentClick = onCommentClick,
            onCollectClick = {
                val newIsCollected = !isCollected // 先计算新状态
                setIsCollected(newIsCollected)
                if (newIsCollected) {
                    scope.launch {
                        MyRetrofitDatasource.collectPost(postInfo.id, SessionManager.currentUser?.id!!)
                        // 提示收藏成功
                        Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    scope.launch {
                        MyRetrofitDatasource.unCollectPost(postInfo.id, SessionManager.currentUser?.id!!)
                        // 提示取消收藏
                        Toast.makeText(context, "取消收藏", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        )
        Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
        //点赞量
        androidx.compose.material3.Text(
            text = "${likes}次赞",
            fontSize = 12.sp,
            modifier = Modifier.padding(start = 8.dp)
        )
        Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
        //文案
        ClickableText(
            text = buildAnnotatedString {
                val text =
                    if (isExpanded) postInfo.content else "${postInfo.content?.take(50)}...展开"
                append(text)
                if (!isExpanded) {
                    text?.let {
                        addStyle(
                            style = SpanStyle(color = InstagramDarkGray),
                            start = text.length - 3,
                            end = it.length
                        )
                    }
                }
            },
            style = TextStyle(fontSize = 12.sp),
            modifier = Modifier
                .padding(start = 8.dp)
                .clickable { isExpanded = !isExpanded }, // 添加 onClick 回调
            overflow = TextOverflow.Ellipsis,
            maxLines = if (isExpanded) Int.MAX_VALUE else 2, // 设置 maxLines
            onClick = { isExpanded = !isExpanded } // 添加 onClick 回调
        )
        Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
        //评论量
        androidx.compose.material3.Text(
            text = "共${postInfo.commentCount}条评论",
            fontSize = 12.sp,
            color = InstagramDarkGray,
            modifier = Modifier
                .padding(start = 8.dp)
                .clickableNoRipple {
                    // 打开评论抽屉
                    onCommentClick()
                }
        )
//        Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
//        //头像 + ”添加评论“
//        Row(
//            modifier = Modifier.fillMaxWidth(),
//            verticalAlignment = Alignment.CenterVertically
//        ) {
//            Spacer(modifier = Modifier.size(8.dp))
//            AsyncImage(
//                model = postInfo.user.avatar?.let {
//                    val url = "${Config.ADDRESS}avatars/$it"
//                    Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
//                    url
//                } ?: run {
//                    Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
//                    R.drawable.ic_default_avatar
//                },
//                contentDescription = "发布者头像",
//                modifier = Modifier
//                    .size(30.dp)
//                    .clip(CircleShape)
//                    .background(Color.Transparent),
//                contentScale = ContentScale.Crop,
//                error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
//            )
//            Spacer(modifier = Modifier.size(6.dp))
//            androidx.compose.material3.Text(
//                text = "添加评论...",
//                fontSize = 12.sp,
//                color = InstagramDarkGray
//            )
//        }
        Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
        //发布日期
        postInfo.createdTime?.let {
            Text(
                text = it,
                fontSize = 10.sp,
                color = InstagramDarkGray,
                modifier = Modifier.padding(start = 8.dp)
            )
        }
    }
}


@Composable
fun ImageCarousel(
    postInfo: PostInfo,
    isLiked: Boolean,
    isCollected: Boolean,
    onLikeClick: () -> Unit,
    isAutoPlay: Boolean, // 新增参数,
    viewModel: HomeViewModel = viewModel(),
    onCommentClick: () -> Unit,
    onCollectClick: () -> Unit,
) {
    // 新增独立的手动控制状态
    var manualPlayState by remember { mutableStateOf(true) }
    val mediaList = postInfo.urls
    val pagerState = rememberPagerState()
    val scope = rememberCoroutineScope()
    var currentIndex by remember { mutableIntStateOf(0) }

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }
            .collect { index ->
                currentIndex = index
            }
    }

    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        val context = LocalContext.current

        HorizontalPager(
            count = mediaList.size,
            state = pagerState,
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .wrapContentHeight() // 改为自适应高度
        ) { page ->
            val uri = mediaList[page]
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center)
            ) {
                if (uri.endsWith(".mp4")) {

                    val url = "${Config.ADDRESS}video/$uri"
                    Log.d("HomeRoute", "🟢 尝试加载视频 URL: $url")
                    val exoPlayer = remember(context) {
                        ExoPlayer.Builder(context).build().apply {
                            setMediaItem(MediaItem.fromUri(url))
                            addListener(object : Player.Listener {
                                override fun onPlaybackStateChanged(state: Int) {
                                    if (state == Player.STATE_READY && isAutoPlay) {
                                        play() // 确保准备完成后立即播放
                                    }
                                }
                            })
                            prepare()
                        }
                    }

                    // 自动播放控制
                    LaunchedEffect(isAutoPlay) {
                        if (isAutoPlay) {
                            exoPlayer.playWhenReady = true
                            manualPlayState = true
                        } else {
                            exoPlayer.pause()
                            manualPlayState = false
                        }
                    }

                    // 生命周期管理
                    DisposableEffect(Unit) {
                        viewModel.registerPlayer(postInfo.id, exoPlayer)
                        onDispose {
                            viewModel.unregisterPlayer(postInfo.id)
                            exoPlayer.release()
                        }
                    }
                    // 视频播放层
                    AndroidView(
                        factory = { ctx ->
                            PlayerView(ctx).apply {
                                player = exoPlayer
                                useController = false
                            }
                        },
                        modifier = Modifier
                            .fillMaxSize()
                            .clickable {
                                //isPlaying = !isPlaying
                                manualPlayState = !manualPlayState
                                exoPlayer.playWhenReady = manualPlayState
                            }
                            .background(Color.Black) // 添加背景色以便调试
                            .pointerInput(Unit) {
                                detectTapGestures(
                                    onTap = {
                                        // 单击：切换播放/暂停
                                        exoPlayer.playWhenReady = !exoPlayer.playWhenReady
                                    },
                                )
                            }
                    )

                } else {
                    AsyncImage(
                        model = mediaList[page].let {
                            val url = "${Config.ADDRESS}avatars/$it"
                            Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
                            url
                        },
                        contentDescription = "帖子图片",
                        modifier = Modifier
                            .fillMaxSize(),
                        contentScale = ContentScale.Fit,
                        error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                    )
                }
            }
        }

        // 图片指示器
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左边的 like, comment, share 图标
            Row(
                modifier = Modifier.weight(1f),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                AnimatedContent(targetState = isLiked) { targetIsLiked ->
                    Image(
                        painter = painterResource(id = if (targetIsLiked) R.drawable.heart_filled else R.drawable.heart),
                        contentDescription = "like",
                        modifier = Modifier
                            .size(24.dp)
                            .clickable {
                                onLikeClick()
                            }
                    )
                }
                Spacer(modifier = Modifier.size(15.dp)) // 添加间隔
                Image(
                    painter = painterResource(id = R.drawable.comment),
                    contentDescription = "comment",
                    modifier = Modifier
                        .size(24.dp)
                        .clickableNoRipple {
                            // 打开评论区抽屉
                            onCommentClick()
                        }
                )
                Spacer(modifier = Modifier.size(15.dp)) // 添加间隔
                Image(
                    painter = painterResource(id = R.drawable.share),
                    contentDescription = "share",
                    modifier = Modifier.size(24.dp)
                )
            }

            // 中间的图标指示器
            Row(
                modifier = Modifier.weight(1f),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                mediaList.forEachIndexed { index, _ ->
                    val size = if (index == currentIndex) 8.dp else 5.dp
                    val color = if (index == currentIndex) Color.Blue else Color.Gray

                    Box(
                        modifier = Modifier
                            .size(size)
                            .clip(CircleShape)
                            .background(color)
                            .clickable {
                                scope.launch {
                                    pagerState.scrollToPage(index)
                                }
                            }
                    )
                    if (index < mediaList.size - 1) {
                        Spacer(modifier = Modifier.size(4.dp)) // 添加间隔
                    }
                }
            }

            // 右边的 collection 图标
            Row(
                modifier = Modifier.weight(1f),
                horizontalArrangement = Arrangement.End,
                verticalAlignment = Alignment.CenterVertically
            ) {
                AnimatedContent(targetState = isCollected) { targetIsCollected ->
                    Image(
                        painter = painterResource(id = if (targetIsCollected) R.drawable.collection_filled else R.drawable.collection),
                        contentDescription = "like",
                        modifier = Modifier
                            .size(24.dp)
                            .clickable {
                                onCollectClick()
                            }
                    )
                }
            }
        }
    }
}

@Composable
fun RecommendUserList(
    userInfoList: List<UserInfo>,
    toProfile: (String) -> Unit,
) {
    LazyRow(
        modifier = Modifier.padding(start = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        items(userInfoList.size) {
            RecommendUserItem(userInfoList[it], toProfile)
        }
    }
}

@Composable
fun RecommendUserItem(
    userInfo: UserInfo,
    toProfile: (String) -> Unit,

    ) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        AsyncImage(
            model = userInfo.avatar?.let {
                val url = "${Config.ADDRESS}avatars/$it"
                Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
                url
            } ?: run {
                Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
                R.drawable.ic_default_avatar
            },
            contentDescription = "用户头像",
            modifier = Modifier
                .size(90.dp)
                .clip(CircleShape)
                .clickableNoRipple {
                    userInfo.id?.let { toProfile(it) }
                },
            contentScale = ContentScale.Crop,
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )
        Spacer(modifier = Modifier.size(8.dp)) // 添加间距
        userInfo.nickName?.let {
            Text(
                text = it,
                fontSize = 10.sp,
                modifier = Modifier.padding(start = 4.dp, end = 4.dp) // 添加左右内边距
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeTopBar(
    toLikeMessage: () -> Unit,
    toFriend: () -> Unit,
    toFollowingMedia: () -> Unit,
    toNotification: () -> Unit
) {
    TopAppBar(
        title = { },
        navigationIcon = {
            Row(
                modifier = Modifier.padding(end = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Image(
                    painter = painterResource(id = R.drawable.ins),
                    contentDescription = "ins",
                    modifier = Modifier
                        .size(100.dp) // 放大 ins 图标
                        .padding(start = 8.dp)
                )
                Image(
                    painter = painterResource(id = R.drawable.arrow_down),
                    contentDescription = "已关注",
                    modifier = Modifier
                        .size(24.dp)
                        .padding(start = 4.dp) // 添加间距
                        .clickableNoRipple {
                            //跳转到已关注的媒体信息
                            toFollowingMedia()
                        }
                )
            }
        },
        actions = {
            Row {
                Image(
                    painter = painterResource(id = R.drawable.heart),
                    contentDescription = "谁赞了我",
                    modifier = Modifier
                        .size(35.dp)
                        .padding(end = 4.dp) // 添加间距
                        .clickableNoRipple {
                            toNotification()
                        }
                )
                Spacer(modifier = Modifier.size(15.dp)) // 添加间距
                Image(
                    painter = painterResource(id = R.drawable.messenger),
                    contentDescription = "聊天",
                    modifier = Modifier
                        .size(35.dp)
                        .padding(end = 4.dp) // 添加间距
                        .clickable {
                            toFriend()
                        }
                )
            }
        },
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors().copy(
            containerColor = Color.Transparent
        )
    )
}

@Preview
@Composable
fun HomeScreenPreview() {
    //HomeScreen()
}
